import 'dart:async';
import 'dart:io';
import 'dart:developer' as developer;

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:full_display/common/qxp_color.dart';
import 'package:full_display/common/qxp_style.dart';
import 'package:full_display/generated/l10n.dart';
import 'package:full_display/page/single/single_add_page.dart';
import 'package:full_display/page/single/single_nodevice_page.dart';
import 'package:full_display/page/single/single_provider.dart';
import 'package:full_display/page/single/single_setting_page.dart';
import 'package:full_display/provide/cmd_provider.dart';
import 'package:full_display/routers/route_name.dart';
import 'package:full_display/unit/navigation/navigation_util.dart';
import 'package:full_display/unit/screen/screen_utility.dart';
import 'package:full_display/unit/asset_utils/asset_utils.dart';
import 'package:full_display/unit/web_socket/web_sockect_utils.dart';
import 'package:full_display/unit/widgets/drawer/drawer_widget.dart';
import 'package:connectivity/connectivity.dart';
import 'package:full_display/unit/widgets/widget_dialog/bluetooth_setting_dialog.dart';
import 'package:full_display/unit/widgets/widget_dialog/clock_dialog.dart';
import 'package:full_display/unit/widgets/widget_dialog/widget_dialog.dart';
import 'package:full_display/unit/widgets/widget_dialog/wifi_setting_dialog.dart';
import 'package:network_info_plus/network_info_plus.dart';
import 'package:provider/provider.dart';
import 'package:app_settings/app_settings.dart';

final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey();

class SinglePage extends StatefulWidget {
  const SinglePage({super.key});

  @override
  State<SinglePage> createState() => _SinglePageState();
}

class _SinglePageState extends State<SinglePage> {
  late CMDProvider _cmdData;
  final NetworkInfo _networkInfo = NetworkInfo();
  final Connectivity _connectivity = Connectivity();
  late StreamSubscription<ConnectivityResult> _connectivitySubscription;
  TextEditingController passwordController = TextEditingController();
  TextEditingController wifiNameController = TextEditingController();
  TextEditingController nameController = TextEditingController();

  @override
  void initState() {
    super.initState();

    initConnectivity();
    _connectivitySubscription =
        _connectivity.onConnectivityChanged.listen(_updateConnectionStatus);
  }

  @override
  void dispose() {
    _connectivitySubscription.cancel();
    super.dispose();
  }

  Future<void> initConnectivity() async {
    ConnectivityResult result = ConnectivityResult.none;
    try {
      result = await _connectivity.checkConnectivity();
    } on PlatformException catch (e) {}
    if (!mounted) {
      return Future.value(null);
    }

    return _updateConnectionStatus(result);
  }

  Future<void> _updateConnectionStatus(ConnectivityResult result) async {
    _initNetworkInfo();
  }

  Future<void> _initNetworkInfo() async {
    String wifiName = '';

    try {
      if (!kIsWeb && Platform.isIOS) {
        // ignore: deprecated_member_use
        var status = await _networkInfo.getLocationServiceAuthorization();

        wifiName = await _networkInfo.getWifiName() ?? '';

        if (wifiName.isNotEmpty) {
          if (!(wifiName.contains('xlz') || wifiName.contains('XLZ'))) {
            print("=========>12${wifiName}");
            _cmdData.clearInfo();
          }
        }
        _cmdData.getWifiName(wifiName);
      }
    } on PlatformException catch (e) {
      developer.log('Failed to get Wifi Name', error: e);
    }
  }

  @override
  Widget build(BuildContext context) {
    _cmdData = context.watch<CMDProvider>();
    print("======>${_cmdData.deviceID}");
    return Scaffold(
      backgroundColor: ColorPlate.background,
      resizeToAvoidBottomInset: false,
      drawer: DrawerWidget(),
      onDrawerChanged: (isOpened) {
        if (isOpened == false) {
          WebSocketUtils().sendMessage(18);
        }
      },
      key: _scaffoldKey,
      appBar: AppBar(
        backgroundColor: ColorPlate.background,
        elevation: 0,
        leading: _cmdData.deviceID.isEmpty
            ? Container()
            : IconButton(
                icon: Image.asset(
                    height: 20.0.H,
                    width: 20.0.W,
                    AssetUtils.getAsset2Image("icon_fold")),
                onPressed: () {
                  _scaffoldKey.currentState?.openDrawer();
                },
              ),
        actions: _cmdData.deviceID.isEmpty
            ? [
                IconButton(
                  icon: Image.asset(
                    height: 20.0.H,
                    width: 20.0.W,
                    AssetUtils.getAsset2Image("icon_add"),
                  ),
                  onPressed: () {
                    AppSettings.openWIFISettings(callback: () {
                      print(" ---callback  ");
                    });
                  },
                ),
              ]
            : [
                IconButton(
                  icon: Image.asset(
                    height: 24.0.H,
                    width: 24.0.W,
                    AssetUtils.getAsset2Image("icon_wifi"),
                  ),
                  onPressed: () {
                    settingdialog(0, context);
                  },
                ),
                IconButton(
                  icon: Image.asset(
                    height: 24.0.H,
                    width: 24.0.W,
                    AssetUtils.getAsset2Image("icon_bluetooth"),
                  ),
                  onPressed: () {
                    settingdialog(1, context);
                  },
                ),
                IconButton(
                  icon: Image.asset(
                    height: 24.0.H,
                    width: 24.0.W,
                    AssetUtils.getAsset2Image("icon_clock"),
                  ),
                  onPressed: () {
                    settingdialog(2, context);
                  },
                ),
                IconButton(
                  icon: Image.asset(
                    height: 24.0.H,
                    width: 24.0.W,
                    AssetUtils.getAsset2Image("icon_add"),
                  ),
                  onPressed: () {
                    // NavigationUtil.getInstance().pushPage(
                    //   context,
                    //   RouteNames.singleSettingPage,
                    //   widget: const SingleSettingPage(),
                    // );

                    // NavigationUtil.getInstance().pushPage(
                    //     context, RouteNames.singleAddPage,
                    //     widget: const SingleAddPage());
                    AppSettings.openWIFISettings(callback: () {
                      print(" ---callback  ");
                    });
                  },
                ),
              ],
      ),
      body: _cmdData.deviceID.isEmpty
          ? const SingleNoDevicePage()
          : const SingleAddPage(),
      // const SingleAddPage(),
    );
  }

  //WiFi 设置方法
  void settingdialog(int index, BuildContext context) {
    if (index == 0) {
      showDialog(
        barrierDismissible: true,
        context: context,
        builder: (context) {
          return DialogWidget(
            contentWidget: WifiSettingDialog(
              wifiName: _cmdData.wifiName.isEmpty ? "" : _cmdData.wifiName,
              pwd: "",
              okBtnTap: () {
                print(
                  "${S.of(context).input_text}${passwordController.text}",
                );
              },
              pwdvc: passwordController,
              namevc: wifiNameController,
              cancelBtnTap: () {},
            ),
          );
        },
      );
    } else if (index == 1) {
      showDialog(
        barrierDismissible: true,
        context: context,
        builder: (context) {
          return DialogWidget(
            contentWidget: BluetoothSettingDialog(
              bluetoothName: "",
              okBtnTap: () {
                String name = nameController.text;
                print("name======>${name}");
                // WebSocketUtils().sendCustomMessage(48,
                //     content: {"bluetooth": name, "password": ""});
                nameController.text = '';
              },
              vc: nameController,
              cancelBtnTap: () {},
            ),
          );
        },
      );
    } else {
      showDialog(
        context: context,
        barrierDismissible: true,
        builder: (context) {
          return ClockDialog();
        },
      );
    }
  }
}
